package com.patrol.controller;

import com.patrol.dao.WrjVideoDao;
import com.patrol.pojo.WrjVideo;
import com.patrol.utils.Result;
import io.swagger.annotations.ApiOperation;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.FrameRecorder;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;
import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.ffmpeg.global.avutil;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wrj")
public class SendMessageController {

    @Value("${patrol.path.video}")
    private String videoPath;

    @Resource
    private WrjVideoDao wrjVideoDao;

//    private int num_picture[] = new int[100];
    private Map<String, Integer> map = new HashMap<String, Integer>();
    private static String video_now_name = "none";
    private static int video_now_index = 0;
    private static int video_now_num = 0;
    //设置每秒的帧数
    private static final Integer FRAME = 5;
    //设置一秒钟几幅图像
    private static final Integer SECOND_IMG = 3;
    private static int keep_video_num = 10;
    private static int FRAME_second = 15;

    @PostMapping("/sendSomeMsg}")
    public Result sendSomeMsg(HttpServletRequest request) throws FrameRecorder.Exception {
        String a = request.getParameter("salary");
        System.out.println(a);
        String b = request.getParameter("image");
        String c = request.getParameter("usr");
        if (c.length() > 0) {
            String file_base_pwd = "D:\\a_jV\\log\\";
            String file_pwd = file_base_pwd + c;
            File folder = new File(file_pwd);
            if (!folder.exists() && !folder.isDirectory()) {
                folder.mkdirs();
                System.out.println("创建文件夹:" + file_pwd);
            }
            int time_num = 0;
            if (map.get(c) == null){
                map.put(c, 0);
            } else {
                time_num = map.get(c);
            }
            if (keep(b, file_pwd + "\\" + String.valueOf(time_num) + ".jpg") == 1) {
                System.out.println("finish" + String.valueOf(time_num));
                if (time_num % keep_video_num == 0) {
                    if (video_get(c) == 1) {
                        System.out.println("video保存成功");
                    }
                }
                time_num ++ ;
                map.put(c, time_num);
            }

            return Result.ok();
        }
//        System.out.println(b);
//        MultiValueMap<String, MultipartFile> map = request.getMultiFileMap();
//        byte[] decodeBytes = java.util.Base64.getDecoder().decode(b);
        byte[] decodeBytes;
        try{
//            decodeBytes = new String(Base64.decodeBase64(b.getBytes("UTF-8")), "UTF-8");
//            decodeBytes = Base64.decodeBase64(b.getBytes("UTF-8"));
//            System.out.println(decodeBytes);
//            sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
            BASE64Decoder decoder = new BASE64Decoder();

            decodeBytes = decoder.decodeBuffer(b);
        } catch (UnsupportedEncodingException e) {
//            logger.error(inputData, e);
            System.out.println("decode error");
            return Result.fail();
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail();
        }
        try{
//            File file =new File("D:\\a_jV\\a.jpg");
//            if(!file.exists()){
//                file.createNewFile();
//            }
//            FileWriter fileWritter = new FileWriter(file.getName());
//            BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
//            bufferWritter.write(decodeBytes);
//            bufferWritter.close();
//            FileOutputStream fos = new FileOutputStream("D:\\a_jV\\a.jpg",false);
            FileOutputStream fos = new FileOutputStream("/root/a.jpg",false);
            fos.write(decodeBytes);
            fos.close();
            System.out.println("finish");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.ok();
    }

    private int keep(String b, String file_pwd) {
        byte[] decodeBytes;
        try{
//            decodeBytes = new String(Base64.decodeBase64(b.getBytes("UTF-8")), "UTF-8");
//            decodeBytes = Base64.decodeBase64(b.getBytes("UTF-8"));
//            System.out.println(decodeBytes);
//            sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
            BASE64Decoder decoder = new BASE64Decoder();

            decodeBytes = decoder.decodeBuffer(b);
        } catch (UnsupportedEncodingException e) {
//            logger.error(inputData, e);
            System.out.println("decode error");
            return 0;
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }
        try{
//            File file =new File("D:\\a_jV\\a.jpg");
//            if(!file.exists()){
//                file.createNewFile();
//            }
//            FileWriter fileWritter = new FileWriter(file.getName());
//            BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
//            bufferWritter.write(decodeBytes);
//            bufferWritter.close();
//            FileOutputStream fos = new FileOutputStream("D:\\a_jV\\a.jpg",false);
            FileOutputStream fos = new FileOutputStream(file_pwd,false);
            fos.write(decodeBytes);
            fos.close();
            System.out.println("finish");

        } catch (IOException e) {
            e.printStackTrace();
        }
        return 1;
    }

    private int video_get(String c) throws FrameRecorder.Exception {
//        String video_name = "D:\\a_jV\\video\\" + c + "\\" + String.valueOf(video_now_index) + ".mp4";
        String video_name = videoPath + c + "\\" + String.valueOf(video_now_index) + ".mp4";
        String dir_name =  videoPath + c;
        File ff = new File(dir_name);
//        if (ff)
        if (createMp4(video_name, 640, 480, c) == 1) {
            System.out.println("keep video success! keep to " + video_name);
            video_now_index ++ ;
            video_now_name = video_name;
        }
        return 1;
    }

    private static int createMp4(String localPath, int width, int height, String c) throws FrameRecorder.Exception {
        long startTime = System.currentTimeMillis();
        //视频宽高最好是按照常见的视频的宽高  16：9  或者 9：16
        System.out.println(localPath);
        FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(localPath, width, height);
        //设置视频编码层模式
        recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);
        //设置视频多少帧每秒
        recorder.setFrameRate(FRAME_second);
        //设置视频图像数据格式
        recorder.setPixelFormat(avutil.AV_PIX_FMT_YUV420P);
        //视频格式  可以自己选
        recorder.setFormat("mp4");
        try {
            recorder.start();
            Java2DFrameConverter converter = new Java2DFrameConverter();
            //录制一个自定义视频
            Integer index = 0;
            for (; index < keep_video_num; index++) {
                BufferedImage read = ImageIO.read(picture_get(c, index + video_now_num));
                //根据帧数  记录每一帧都是一样的
                for (int j = 0; j < FRAME; j++) {
                    recorder.record(converter.getFrame(read));
                }
            }
            video_now_num += keep_video_num;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        } finally {
            //最后一定要结束并释放资源
            recorder.stop();
            recorder.release();
        }
        System.out.println("生成视频结束==>"+(System.currentTimeMillis()-startTime));
        return 1;
    }

    private static File picture_get(String c,int index) {
        String file_name = "D:\\a_jV\\log\\" + c + "\\" + String.valueOf(index) + ".jpg";
        System.out.println(file_name);
        return new File(file_name);
    }

    @ApiOperation(value = "根据无人机编号查询实时录像,有一分钟的延时")
    @GetMapping("/getVideoById/{wrjId}")
    public Result getVideoById(@PathVariable String wrjId) {
        WrjVideo wrjVideo = wrjVideoDao.selectWrjVideoById(wrjId);
        return Result.ok(wrjVideo);
    }

    @RequestMapping(path = "/Info/{fileName}", method = RequestMethod.GET)
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        // 服务器存放路径
        fileName = videoPath + "/" + fileName;
        // 文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        // 响应图片
        response.setContentType("image/" + suffix);
        try (
                FileInputStream fis = new FileInputStream(fileName);
                OutputStream os = response.getOutputStream();
        ) {
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fis.read(buffer)) != -1) {
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("失败！！");
        }
    }
}